package cn.lx.elasticsearch.autocomplete.controller;

import cn.lx.elasticsearch.autocomplete.dto.SuggestRequest;
import cn.lx.elasticsearch.autocomplete.dto.SuggestResponse;
import cn.lx.elasticsearch.autocomplete.entity.City;
import cn.lx.elasticsearch.autocomplete.entity.Product;
import cn.lx.elasticsearch.autocomplete.entity.User;
import cn.lx.elasticsearch.autocomplete.service.AutocompleteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 自动补全控制器
 * 
 * @author lx
 * @since 2024-01-01
 */
@Slf4j
@RestController
@RequestMapping("/api/autocomplete")
@CrossOrigin(origins = "*")
public class AutocompleteController {

    @Autowired
    private AutocompleteService autocompleteService;

    /**
     * 商品自动补全
     * 
     * @param request 请求参数
     * @return 建议结果
     */
    @PostMapping("/products")
    public ResponseEntity<SuggestResponse<Product>> suggestProducts(@Valid @RequestBody SuggestRequest request) {
        log.info("商品自动补全请求：{}", request);
        
        // 设置索引类型
        request.setIndexType("product");
        
        SuggestResponse<Product> response = autocompleteService.suggestProducts(request);
        return ResponseEntity.ok(response);
    }

    /**
     * 城市自动补全
     * 
     * @param request 请求参数
     * @return 建议结果
     */
    @PostMapping("/cities")
    public ResponseEntity<SuggestResponse<City>> suggestCities(@Valid @RequestBody SuggestRequest request) {
        log.info("城市自动补全请求：{}", request);
        
        // 设置索引类型
        request.setIndexType("city");
        
        SuggestResponse<City> response = autocompleteService.suggestCities(request);
        return ResponseEntity.ok(response);
    }

    /**
     * 用户自动补全
     * 
     * @param request 请求参数
     * @return 建议结果
     */
    @PostMapping("/users")
    public ResponseEntity<SuggestResponse<User>> suggestUsers(@Valid @RequestBody SuggestRequest request) {
        log.info("用户自动补全请求：{}", request);
        
        // 设置索引类型
        request.setIndexType("user");
        
        SuggestResponse<User> response = autocompleteService.suggestUsers(request);
        return ResponseEntity.ok(response);
    }

    /**
     * 通用自动补全接口
     * 
     * @param indexType 索引类型
     * @param request 请求参数
     * @return 建议结果
     */
    @PostMapping("/{indexType}")
    public ResponseEntity<Map<String, Object>> suggest(@PathVariable String indexType, 
                                                      @Valid @RequestBody SuggestRequest request) {
        log.info("通用自动补全请求，索引类型：{}，请求参数：{}", indexType, request);
        
        // 设置索引类型
        request.setIndexType(indexType);
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            switch (indexType.toLowerCase()) {
                case "product":
                    SuggestResponse<Product> productResponse = autocompleteService.suggestProducts(request);
                    result.put("data", productResponse);
                    break;
                case "city":
                    SuggestResponse<City> cityResponse = autocompleteService.suggestCities(request);
                    result.put("data", cityResponse);
                    break;
                case "user":
                    SuggestResponse<User> userResponse = autocompleteService.suggestUsers(request);
                    result.put("data", userResponse);
                    break;
                default:
                    result.put("success", false);
                    result.put("message", "不支持的索引类型：" + indexType);
                    return ResponseEntity.badRequest().body(result);
            }
            
            result.put("success", true);
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("自动补全查询失败", e);
            result.put("success", false);
            result.put("message", e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 初始化测试数据
     * 
     * @return 操作结果
     */
    @PostMapping("/init-data")
    public ResponseEntity<Map<String, Object>> initTestData() {
        log.info("开始初始化测试数据");
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            autocompleteService.initTestData();
            result.put("success", true);
            result.put("message", "测试数据初始化成功");
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("初始化测试数据失败", e);
            result.put("success", false);
            result.put("message", "初始化测试数据失败：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 健康检查接口
     * 
     * @return 健康状态
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> health() {
        Map<String, Object> result = new HashMap<>();
        result.put("status", "UP");
        result.put("service", "Elasticsearch Autocomplete Service");
        result.put("timestamp", System.currentTimeMillis());
        return ResponseEntity.ok(result);
    }

    /**
     * 获取支持的索引类型
     * 
     * @return 索引类型列表
     */
    @GetMapping("/index-types")
    public ResponseEntity<Map<String, Object>> getIndexTypes() {
        Map<String, Object> result = new HashMap<>();
        
        Map<String, String> indexTypes = new HashMap<>();
        indexTypes.put("product", "商品索引");
        indexTypes.put("city", "城市索引");
        indexTypes.put("user", "用户索引");
        
        result.put("success", true);
        result.put("data", indexTypes);
        
        return ResponseEntity.ok(result);
    }
}
